$(function () {
    od.current_file = "f1"
    od.files = []
    od.select_file = null

    $(".sortable" ).sortable({
        connectWidth:".sortable",
        handle:'.drag'
    })
    $( ".draggable" ).draggable({
        connectToSortable: ".sortable",
        helper: "clone",
        handle:".drag",
        stop:function(e,t){
            $("#editor .sortable" ).sortable({
                connectWidth:".sortable",
                handle:'.drag'
            })
        }
    });
    $("[action-view]").each((index,item)=> {
        let _self = $(item);
        let view = _self.attr("action-view")
        let div = $("<div></div>")
        div.attr("class","view")
        div.html(od[view].templates[0].template)
        _self.append(div)
        _self.selectable(true)
    })
    $("#editor").on("click",".item",function(e) {
        e.stopPropagation()
        if(od.selected != null) {
            od.selected.removeClass("selected")
        }
        let _self = $(this)
        _self.addClass("selected")
        let view = _self.attr("action-view")
        let odMenu = od[view].menu
        let menus = getMenu(view,odMenu)
        let pop_menu = $("#popmenu")
        pop_menu.addClass("pop")
        let bar = "<div class = 'title'>样式<div class = 'close'>X</div></div>"
        pop_menu.html(bar + menus)
        pop_menu.css("left",(e.pageX + 60) + "px")
        pop_menu.css("top","45px")
        od.selected = _self
        od.icon = null
    })
    $("#popmenu").on("click",".title .close",function(e){
        $("#popmenu").removeClass("pop")
    })
    $("#popmenu").on("change","[od-change]",function(e){
        let val = $(this).val()
        let target_view = $(this).parents("[target-view]").attr("target-view")
        let od_change = $(this).attr("od-change")
        od[target_view][od_change](od.selected,val);
    })
    $("#popmenu").on("change","[od-check]",function (e) {
        let isChecked = $(this).prop("checked")
        let target_view = $(this).parents("[target-view]").attr("target-view")
        let od_change = $(this).attr("od-check")
        od[target_view][od_change](od.selected,isChecked);
    })
    $(document).on("keydown",function(e) {
        if(e.keyCode === 46 && od.selected) {
            od.selected.remove()
            $("#popmenu").hide()
            od.selected = null
        }
    })
    $(".tab-bar-item").on("click",function(e) {
        $(this).parent().find(".tab-bar-item").removeClass("active")
        $(this).addClass("active")
        $(this).parent().parent().find(".tab-content-item").removeClass("active")
        let target = $(this).attr("target")
        $("#" + target).addClass("active")
    })
    $("#editor").on("click","[datatype=icon]",function(e) {
        e.stopPropagation()
        if(od.icon != undefined && od.icon != null){
            od.icon.style.border = "none"
        }
        od.icon = e.target
        od.icon.style.border = "solid 1px #F00";
        $(".tab-bar-item").removeClass("active")
        $(".tab-bar-item[target=icon-panel]").addClass("active")
        $(".tab-content-item").removeClass("active")
        let target = $(this).attr("target")
        $("#icon-panel").addClass("active")
    })
    $("#icon-panel").on("click","i",function(e){
        if(od.icon && od.icon != null) {
            od.icon.classList = $(this).attr("class")
        }
    })
    $("#preview-box .close-btn").on("click",function(){
        $("#preview-box").hide()
    })
    $(".view-picker").on("click","li",function(e){
        console.log(111)
        let width = $(this).attr("data-width")
        let height = $(this).attr("data-height")
        let size = $(this).attr("data-size")
        $("#editor").css("width",width + "px")
        $("#editor").css("height",height + "px")
        $("#editor").css("font-size",size + "px")
    })
    $(".filelist").on("dblclick","li",function(e){
        $(this).attr("contenteditable","true")
        var that = this
        $(this).text().change(function(e){
            console.log("123")
            let name_en = $(that).attr("data-file");
            let name = $(that).text()
            for(let file of od.files) {
                if(file.name_en == name_en) {
                    file.name = name
                    break;
                }
            }
            $(this).attr("contenteditable",false)
            localStorage.setItem("okaydesigner",JSON.stringify(od.files))
        })
    })
    $(".filelist").on("click","li",function(e){
        let name_en = $(this).attr("data-file");
        let name = $(this).text()
        for(let file of od.files) {
            if(file.name_en == name_en) {
                $("#editor").html(file.html)
                editor.setValue(file.script)
                break;
            }
        }

        if(od.select_file != null) {
            $(od.select_file).removeClass("active")
        }
        od.select_file = this
        $(od.select_file).addClass("active")

    })

    let sc = document.getElementById("scriptedit")

    window.editor = CodeMirror.fromTextArea(sc, {
        mode: "javascript",
        lineNumbers: true,
    });
    let txt = localStorage.getItem("okaydesigner")
    if(txt && txt != "") {
        let data = JSON.parse(txt)
        od.files = data
        if(od.files.length > 0) {
            od.current_file = od.files[0].name_en
            $("#editor").html(od.files[0].html)
            editor.setValue(od.files[0].script)
        }else {
            let init = {
                name:'文件1',
                name_en:Math.random().toString(36).substr(2),
                html:"",
                script:""
            }
            od.current_file = init.name_en
            od.files.push(init)
        }
    }else {
        let init = {
            name:'文件1',
            name_en:Math.random().toString(36).substr(2),
            html:"",
            script:""
        }
        od.current_file = init.name_en
        od.files.push(init)
    }
    refreshFileList()
    od.select_file = $("ul.filelist").children(":first")
    od.select_file.addClass("active")
})
//递归遍历父菜单
function getMenu(_v,_cur) {
    let self_menu = `<div target-view = '${_v}'>${_cur.template}</div>`
    if(_cur.extends == 'undefined') {
        return self_menu
    }
    if(od[_cur.extends] == undefined) {
        return self_menu
    }
    let _p = od[_cur.extends].menu
    return self_menu + getMenu(od[_cur.extends].name,_p)

}
//预览
function preview() {
    //提取元素
    let dv = $("<div></div>")
    let c = $("#editor");
    dv.html(c.html())
    dv.find(".preview").remove()
    dv.find(".drag").remove()

    dv.find(".view").each((i,e)=> {
        $(e).parent().append($(e).children())
        $(e).remove()
    })

    dv.find(".draggable").each((i,e) => {
        $(e).parent().append($(e).children())
        $(e).remove()
    })
    let iframe = document.createElement("iframe")
    $("#preview").html(iframe)
    $(iframe).attr("width","375px")
    $(iframe).attr("height","667px")
    let _ifr_doc = iframe.contentDocument || iframe.contentWindow.document
    let html = '<!doctype html><html>' +
        '<head>' +
        '<meta charset="utf-8">' +
        '<meta name="viewport" content="width=device-width,minimum-scale=1.0,maximum-scale=1.0"/>' +
        '<link rel="stylesheet" href="css/aui.css">' +
        '<link rel="stylesheet" href="https://cdn.bootcss.com/font-awesome/4.7.0/css/font-awesome.css">' +
        '</head>' +
        '<body>' +
        dv.html() +
        '</body>' +
        '<script>' +
        editor.getValue() +

        '</script>' +
        '</html>'
    _ifr_doc.write(html)
    $("#preview-box").show()

}
function orientation() {
    let editor = $("#editor")
    let width = editor.css("width")
    let height = editor.css("height")
    editor.css("width",height)
    editor.css("height",width)

}
function save() {
    let html = $("#editor").html()
    let script = editor.getValue()
    //更新当前文件的内容
    let cf = {};
    for(let file of od.files) {
        if(file.name_en == od.current_file) {
            cf = file
            break;
        }
    }
    cf.html = html
    cf.script = script
    localStorage.setItem("okaydesigner",JSON.stringify(od.files))
    alert("保存成功")
}
function refreshFileList() {
    let filelist = ""
    for(let file of od.files){
        filelist += '<li data-file = "' +file.name_en+ '"><i class = "fa fa-file-o"></i>&nbsp;&nbsp;'+ file.name+'</li>'
    }
    $("ul.filelist").html(filelist)
}
function newFile() {
    var name = prompt("请输入文件名","")
    if(name != null && name != "") {
        let name_en = Math.random().toString(36).substr(2)
        let obj = {
            name:name,
            name_en:name_en,
            html:"",
            script:""
        }
        od.files.push(obj)

        $("#editor").html(obj.html)
        editor.setValue(obj.script)
        if(od.select_file != null) {
            $(od.select_file).removeClass("active")
        }
        refreshFileList()
        od.select_file = $("ul.filelist").children(":last")
        $(od.select_file).addClass("active")
        od.current_file = name_en
        localStorage.setItem("okaydesigner",JSON.stringify(od.files))
    }else {
        alert("文件名不能为空")
    }
}

function deleteFile() {
    let index = -1
    for(let i = 0;i < od.files.length;i++) {
        if(od.files[i].name_en == od.current_file){
            index = i
            break
        }
    }
    if(index == -1){
        return
    }
    od.files.splice(index,1)
    refreshFileList()
    if(od.files.length <= 0) {
        od.current_file = ""
        od.select_file = null
        return
    }
    od.current_file = od.files[0].name_en
    od.select_file = $("ul.filelist").children(":first")
    $("#editor").html(od.files[0].html)
    editor.setValue(od.files[0].script)
    localStorage.setItem("okaydesigner",JSON.stringify(od.files))
}
function downPic() {
    let tmd = document.createElement("div")
    let dv = $(tmd)
    let c = $("#editor");
    dv.html(c.html())
    dv.find(".preview").remove()
    dv.find(".drag").remove()

    dv.find(".view").each((i,e)=> {
        $(e).parent().append($(e).children())
        $(e).remove()
    })

    dv.find(".draggable").each((i,e) => {
        $(e).parent().append($(e).children())
        $(e).remove()
    })
    dv.css("width","375px")
    dv.css("height","667px")
    dv.css("position","absolute");
    dv.css("top","-1000px")
    $(document.body).append(dv)
    convert2canvas(tmd, function(canvas){
        var imgUri = canvas.toDataURL("image/png")
        saveFile(imgUri,$("li[data-file=" + od.current_file +"]").text()+ ".jpg")
        dv.remove()
    })
}
function convert2canvas(dv,fun) {
    var shareContent = dv;
    var width = shareContent.offsetWidth;
    var height = shareContent.offsetHeight;
    var canvas = document.createElement("canvas");
    var scale = 2;

    canvas.width = width * scale;
    canvas.height = height * scale;
    canvas.getContext("2d").scale(scale, scale);

    var opts = {
        scale: scale,
        canvas: canvas,
        logging: true,
        width: width,
        height: height
    };
    html2canvas(shareContent, opts).then(function (canvas) {
        fun(canvas)
    }).catch(err =>{
        console.log(err)
    })
}
function downSrc() {
    //查找当前文件
    for(let file of od.files) {
        let dv = $("<div></div>")
        let c = $("#editor");
        dv.html(c.html())
        dv.find(".preview").remove()
        dv.find(".drag").remove()

        dv.find(".view").each((i,e)=> {
            $(e).parent().append($(e).children())
            $(e).remove()
        })

        dv.find(".draggable").each((i,e) => {
            $(e).parent().append($(e).children())
            $(e).remove()
        })
        if(file.name_en == od.current_file){
            let html = '<!doctype html><html>' +
                '<head>' +
                '<meta charset="utf-8">' +
                '<meta name="viewport" content="width=device-width,minimum-scale=1.0,maximum-scale=1.0"/>' +
                '<link rel="stylesheet" href="css/aui.css">' +
                '<link rel="stylesheet" href="https://cdn.bootcss.com/font-awesome/4.7.0/css/font-awesome.css">' +
                '</head>' +
                '<body>' +
                dv.html() +
                '</body>' +
                '<script>' +
                editor.getValue() +

                '</script>' +
                '</html>'
            saveFile(URL.createObjectURL(new Blob([html])),file.name + ".html")
        }
    }
}

var saveFile = function(data, filename){
    var save_link = document.createElementNS('http://www.w3.org/1999/xhtml', 'a');
    save_link.href = data;
    save_link.download = filename;
    var event = document.createEvent('MouseEvents');
    event.initMouseEvent('click', true, false, window, 0, 0, 0, 0, 0, false, false, false, false, 0, null);
    save_link.dispatchEvent(event);
}
